package com.aiti.lulian.service.impl;

import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.constant.NewCardBusinessConstant;
import com.aiti.lulian.dto.CardUserCardSettingDto;
import com.aiti.lulian.dto.newCard.NewCardUserVersionInfoDto;
import com.aiti.lulian.entity.*;
import com.aiti.lulian.entity.newCard.CardBaseInfo;
import com.aiti.lulian.mapper.CardUserCardSettingMapper;
import com.aiti.lulian.mapper.newCard.CardPersonalBaseInfoMapper;
import com.aiti.lulian.service.*;
import com.aiti.lulian.service.newCard.CardVersionService;
import com.aiti.lulian.vo.CardUserCardSettingDetailVo;
import com.aiti.lulian.vo.CardUserCardSettingVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 个人名片设置表 服务实现类
 * </p>
 *
 * @author 
 * @since 2025-08-11
 */
@Service
public class CardUserCardSettingServiceImpl extends BaseSerivceImpl<CardUserCardSettingMapper, CardUserCardSetting> implements CardUserCardSettingService {

    @Autowired
    private CardUserBackgroundService userBackgroundService;

    @Autowired
    private CardUserCardForwardCoverOptionService cardUserCardForwardCoverOptionService;

    @Autowired
    private CardUserShowFieldOptionService cardUserShowFieldOptionService;

    @Autowired
    private CardUserTemplateService cardUserTemplateService;
    @Autowired
    private CardVersionService cardVersionService;
    @Autowired
    private CardPersonalBaseInfoMapper cardPersonalBaseInfoMapper;


    @Override
    public CardUserCardSettingVo getTemplateSettingByUserId(String userId, String cardId) {
        List<CardUserCardSetting> settingList = this.list(new LambdaQueryWrapper<CardUserCardSetting>().eq(CardUserCardSetting::getUserId, userId).eq(CardUserCardSetting::getCardId, cardId));
        CardUserCardSettingVo cardUserCardSettingVo = new CardUserCardSettingVo();
        if(!CollectionUtils.isEmpty(settingList)){
            CardUserCardSetting cardUserCardSetting = settingList.get(0);
            BeanUtils.copyProperties(cardUserCardSetting, cardUserCardSettingVo);

        }
        NewCardUserVersionInfoDto userVersionInfo = cardVersionService.getUserVersionInfo(userId);
        if(NewCardBusinessConstant.CARD_VERSION_1.equals(userVersionInfo.getCardVersion())) {
            List<CardUserTemplate> templateList = cardUserTemplateService.list(new LambdaQueryWrapper<CardUserTemplate>().in(CardUserTemplate::getFee, 0));
            cardUserCardSettingVo.setUserTemplateList(templateList);
        }else if(userVersionInfo.getOverdue()) {
            List<CardUserTemplate> templateList = cardUserTemplateService.list(new LambdaQueryWrapper<CardUserTemplate>().in(CardUserTemplate::getFee, 0));
            cardUserCardSettingVo.setUserTemplateList(templateList);
        }else {
            List<CardUserTemplate> templateList = cardUserTemplateService.list(new LambdaQueryWrapper<CardUserTemplate>().in(CardUserTemplate::getFee, 0, 1));
            cardUserCardSettingVo.setUserTemplateList(templateList);
        }

        List<CardUserShowFieldOption> showFieldOptionList = cardUserShowFieldOptionService.list(new LambdaQueryWrapper<CardUserShowFieldOption>().orderByAsc(CardUserShowFieldOption::getSort));
        cardUserCardSettingVo.setShowFieldOptionList(showFieldOptionList);

        CardBaseInfo cardBaseInfo = cardPersonalBaseInfoMapper.selectById(cardId);
        if(cardBaseInfo != null){
            String cardVersion = cardBaseInfo.getCardVersion();
            String templateVersion = "unknown";
            /** 名片表中版本。1：个人版，2：试用版，3：付费正式版 4高级版  5拓客版  */
            //模板版本中版本 0为个人版  1为个人付费版 2为企业版
            if("1".equals(cardVersion)){
                templateVersion = "0";
            } else if (("2".equals(cardVersion) || "3".equals(cardVersion)) && StringUtils.isEmpty(cardBaseInfo.getEnterpriseId())) {
                templateVersion = "1";
            } else if (("2".equals(cardVersion) || "3".equals(cardVersion)  || "4".equals(cardVersion)   || "5".equals(cardVersion)) && !StringUtils.isEmpty(cardBaseInfo.getEnterpriseId())) {
                templateVersion = "2";
            }
            List<CardUserCardForwardCoverOption> coverOptionList = cardUserCardForwardCoverOptionService
                    .list(new LambdaQueryWrapper<CardUserCardForwardCoverOption>().eq(CardUserCardForwardCoverOption::getVersion, templateVersion).and(w -> w.and(a->a.isNull(CardUserCardForwardCoverOption::getUserId).eq(CardUserCardForwardCoverOption::getVersion, "0")).or()
                            .eq(CardUserCardForwardCoverOption::getUserId, userId).eq(!StringUtils.isEmpty(cardId),CardUserCardForwardCoverOption::getCardId, cardId)));
            cardUserCardSettingVo.setForwardCoverList(coverOptionList);
        }


        return cardUserCardSettingVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveSetting(CardUserCardSettingDto dto) {
        CardUserCardSetting cardSetting = new CardUserCardSetting();
        BeanUtils.copyProperties(dto, cardSetting);
        this.saveOrUpdate(cardSetting);
        CardUserTemplate cardUserTemplate = cardUserTemplateService.getById(dto.getTemplateId());
        if(cardUserTemplate != null && cardUserTemplate.getFee() == 1) {
            cardVersionService.updateCardUseResourceType(cardSetting.getCardId(), NewCardBusinessConstant.CARD_USE_RESOURCE_TYPE_2);
        }else if(cardUserTemplate != null && cardUserTemplate.getFee() == 0 ){
            cardVersionService.updateCardUseResourceType(cardSetting.getCardId(), NewCardBusinessConstant.CARD_USE_RESOURCE_TYPE_1);
        }

        cardUserCardForwardCoverOptionService.remove(new LambdaQueryWrapper<CardUserCardForwardCoverOption>().eq(CardUserCardForwardCoverOption::getUserId, cardSetting.getUserId()).eq(CardUserCardForwardCoverOption::getCardId, cardSetting.getCardId()));
        List<String> coverList = dto.getCoverList();
        if(coverList != null && coverList.size() > 0){
            CardBaseInfo cardBaseInfo = cardPersonalBaseInfoMapper.selectById(cardSetting.getCardId());

            if(cardBaseInfo != null){
                String cardVersion = cardBaseInfo.getCardVersion();
                String templateVersion;
                /** 名片表中版本。1：个人版，2：试用版，3：付费正式版 4高级版  5拓客版  */
                //模板版本中版本 0为个人版  1为个人付费版 2为企业版
                if("1".equals(cardVersion)){
                    templateVersion = "0";
                } else if (("2".equals(cardVersion) || "3".equals(cardVersion)) && StringUtils.isEmpty(cardBaseInfo.getEnterpriseId())) {
                    templateVersion = "1";
                } else if (("2".equals(cardVersion) || "3".equals(cardVersion)  || "4".equals(cardVersion)   || "5".equals(cardVersion)) && !StringUtils.isEmpty(cardBaseInfo.getEnterpriseId())) {
                    templateVersion = "2";
                } else {
                    templateVersion = "unknown";
                }
                List<CardUserCardForwardCoverOption> saveCoverList = coverList.stream().map(cover -> {
                    CardUserCardForwardCoverOption cardUserCardForwardCoverOption = new CardUserCardForwardCoverOption();
                    cardUserCardForwardCoverOption.setUserId(cardSetting.getUserId());
                    cardUserCardForwardCoverOption.setCardId(dto.getCardId());
                    cardUserCardForwardCoverOption.setUrl(cover);
                    cardUserCardForwardCoverOption.setCustomFlag("1");
                    cardUserCardForwardCoverOption.setVersion(templateVersion);
                    return cardUserCardForwardCoverOption;
                }).collect(Collectors.toList());
                cardUserCardForwardCoverOptionService.saveBatch(saveCoverList);
            }


        }


        return 0;
    }

    @Override
    public CardUserCardSettingDetailVo userSettingDetail(String userId, String cardId) {
        List<CardUserCardSetting> settingList = this.list(new LambdaQueryWrapper<CardUserCardSetting>().eq(CardUserCardSetting::getUserId, userId).eq(CardUserCardSetting::getCardId, cardId));
        CardUserCardSettingDetailVo vo = new CardUserCardSettingDetailVo();
        if(!CollectionUtils.isEmpty(settingList)){
            CardUserCardSetting cardUserCardSetting = settingList.get(0);
            BeanUtils.copyProperties(cardUserCardSetting, vo);
            String templateId = cardUserCardSetting.getTemplateId();
            CardUserTemplate template = cardUserTemplateService.getById(templateId);
            if(template != null){
                vo.setLayoutNum(template.getLayoutNum());
            }


        }
        return vo;

    }

    @Override
    public List<CardUserBackground> backgroundList(String templateId) {
        List<CardUserBackground> backgroundList = userBackgroundService.list(new LambdaQueryWrapper<>(new CardUserBackground()).eq(CardUserBackground::getTemplateId, templateId));
        return backgroundList;
    }

    @Override
    public void updateForwardCoverUrl(CardUserCardSettingDto dto) {
        this.update(new LambdaUpdateWrapper<CardUserCardSetting>().eq(CardUserCardSetting::getCardId, dto.getCardId()).set(CardUserCardSetting::getForwardCoverUrl, dto.getForwardCoverUrl()));
    }
}
